package xyz.xtt.admin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tongtong.middleware.vo.response.AccountBalanceRes;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import xyz.xtt.admin.entity.TblAdminUser;
import xyz.xtt.admin.request.UserLoginRequest;
import xyz.xtt.admin.request.UserRequest;
import xyz.xtt.admin.request.UserSetStatusRequest;
import xyz.xtt.admin.service.IAdminUserService;
import xyz.xtt.admin.vo.AdminUserVo;
import xyz.xtt.common.objects.DozerUtil;
import xyz.xtt.common.response.ApiResult;

import xyz.xtt.admin.utils.Md5Util;
import xyz.xtt.admin.utils.JwtUtil;

import java.net.http.HttpResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-11-21
 */
@RestController
@RequestMapping("/api/admin/admin_user")
public class AdminUserController {

    @Autowired
    private IAdminUserService adminUserService;


    @PostMapping("/login")
    public ApiResult<AdminUserVo> login(@Validated @RequestBody UserLoginRequest userLogin,
                                        HttpServletResponse res) {
        TblAdminUser user = adminUserService.getByName(userLogin.getUsername());
        String password = Md5Util.getMD5String(userLogin.getPassword());
        if (user == null || !password.equals(user.getPassword())) {
            return ApiResult.failure(403, "用户名密码错误");
        }
        if (user.getStatus() != 0) {
            return ApiResult.failure(403, "用户已禁用");
        }
        res.setHeader("uid",String.valueOf(user.getId()));
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        AdminUserVo adminUserVo = DozerUtil.transfor(user, AdminUserVo.class);
        String token = JwtUtil.genToken(map);
        adminUserVo.setToken(token);
        return ApiResult.ok(adminUserVo);
    }

    @GetMapping("/list")
    public ApiResult<Page<AdminUserVo>> list(Integer current, Integer page) {
        current = Optional.ofNullable(current).filter(x -> x < 1).orElse(1);
        page = Optional.ofNullable(page).filter(x -> x < 1).orElse(20);
        return ApiResult.ok(adminUserService.userList(current, page));
    }

    @PostMapping("/create")
    public ApiResult create(@Validated(UserRequest.Add.class)  @RequestBody  UserRequest user) {
        // 查询用户名是否存在
        TblAdminUser adminUser = adminUserService.getByName(user.getUserName());
        if(adminUser != null) {
            return ApiResult.failure(1, "用户名已存在");
        }
        TblAdminUser tblAdminUser = user.create();
        tblAdminUser.setCreateDatetime(LocalDateTime.now());
        return ApiResult.ok(adminUserService.save(tblAdminUser));
    }

    @PostMapping("/update")
    public ApiResult update(@Validated(UserRequest.Update.class) @RequestBody UserRequest user) {
        return ApiResult.ok(adminUserService.update(user));
    }

    @PostMapping("/set_status")
    public ApiResult setStatus(@RequestBody UserSetStatusRequest userSetStatusRequest) {
        if (adminUserService.setStatus(userSetStatusRequest.getId(), userSetStatusRequest.getStatus())) {
            return ApiResult.ok();
        }
        return ApiResult.failure(11, "修改失败");
    }

    @GetMapping("/get_balance")
    public ApiResult<AccountBalanceRes> getBalance() {
        return adminUserService.getBalance();
    }

    @GetMapping("/get")
    public ApiResult<AdminUserVo> get(@Validated @NotNull(message = "ID 不能为空") Integer id) {
        TblAdminUser byId = adminUserService.getById(id);
        if (byId == null) {
            return ApiResult.failure(403, "用户不存在");
        }
        AdminUserVo userVo = DozerUtil.transfor(byId, AdminUserVo.class);
        return ApiResult.ok(userVo);
    }

}
